package qc.module.demo.mapper;

import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.utils.DateUtil;
import qc.module.demo.dto.qzj.QzjDataDto;
import qc.module.demo.dto.qzj.QzjNewDataDto;
import qc.module.demo.entity.Qzj;
import qc.module.demo.entity.enums.QzjChannelTypeEnum;
import qc.module.demo.entity.enums.QzjHandleFlagEnum;
import qc.module.demo.entity.enums.QzjSourceTypeEnum;

import java.util.List;
import java.util.UUID;

/**
 * QzjMapper
 *
 * @author QuCheng Tech
 */
@Mapper
public interface QzjMapper {
    QzjMapper QZJ_MAPPER = Mappers.getMapper(QzjMapper.class);

    @Mapping(target = "tm", ignore = true)
    Qzj toEntity(QzjNewDataDto dto);

    @Mapping(target = "tm", source = "tm", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "updatetm", source = "UPDATETM", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "handletm", source = "HANDLETM", dateFormat = "yyyy-MM-dd HH:mm:ss")
    @Mapping(target = "srctype", source = "SRCTYPE.index")
    @Mapping(target = "chltype", source = "CHLTYPE.name")
    @Mapping(target = "flag", source = "FLAG.name")
    QzjDataDto toDto(Qzj en);

    List<QzjDataDto> toDtoList(List<Qzj> list);

    default Qzj QzjDtoToQzj(QzjNewDataDto dto) {
        //DTO转换为Entity
        Qzj en = QzjMapper.QZJ_MAPPER.toEntity(dto);
        en.setId(UUID.randomUUID().toString());
        //转换时间
        en.setTm(DateUtil.parseDate(dto.getTm()));
        //设置写入时间为当前时间
        en.setUPDATETM(DateUtil.getNowDate());
        //设置处理标记为默认值0，表示未处理
        en.setFLAG(QzjHandleFlagEnum.UN_DEFINE);
        //设置来源类型和通道类型
        en.setSRCTYPE(getQzjSourceTypeEnum(dto.getSrctype()));
        en.setCHLTYPE(getQzjChannelTypeEnum(dto.getChltype()));

        return en;
    }

    static QzjSourceTypeEnum getQzjSourceTypeEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (QzjSourceTypeEnum item : QzjSourceTypeEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return QzjSourceTypeEnum.UN_DEFINE;
    }

    static QzjSourceTypeEnum getQzjSourceTypeEnum(String text) {
        if (StringUtils.isBlank(text)) {
            for (QzjSourceTypeEnum item : QzjSourceTypeEnum.values()) {
                if (item.getName().equals(text)) {
                    return item;
                }
            }
        }
        return QzjSourceTypeEnum.UN_DEFINE;
    }

    static QzjChannelTypeEnum getQzjChannelTypeEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (QzjChannelTypeEnum item : QzjChannelTypeEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return QzjChannelTypeEnum.UN_DEFINE;
    }
}
